package org.orz.cloud.lock;


import org.orz.cloud.lock.zookeeper.ZkLockFactory;
import org.orz.cloud.lock.zookeeper.ZkProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 锁管理者，init()方法用来创建{@link LockHolder}里面的LockFactory对象
 * 其实这里用到的设计模式就是工厂方法模式，核心接口就是{@link Lock}和{@link LockFactory}
 *
 * 在spring启动的时候，初始化的操作就从这个类开始
 */
@Component
@ConditionalOnExpression("${orz.cloud.lock.enable:false}")
public class LockManager {
	@Value("${orz.cloud.lock.type}")
	private String lockType;
	@Value("${orz.cloud.lock.zkLock.url}")
	private String zkLockUrl;

	/**
	 * 初始化LockHolder，并给lockFactory属性初始化
	 */
	@PostConstruct
	public void init(){
		if(lockType == null || "".equals(lockType) || LockProperties.LOCK_TYPE_VAL_ZK.equals(lockType)){
			ZkProperties zkProperties = new ZkProperties();
			zkProperties.setServers(zkLockUrl);

			ZkLockFactory zkLockFactory = new ZkLockFactory();
			zkLockFactory.init(zkProperties);
			LockHolder.getInstance().setLockFactory(zkLockFactory);
		}
	}
}
